<template>
  <div class="body">
    <div class="left-board">
      <div class="logo">{{ title }}</div>
      <div class="logo-bottom">
        <!-- <div>
          <el-form :inline="true" class="demo-form-inline" v-model="form">
            <el-form-item label="名称">
              <el-input placeholder="请输入名称" v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="onSubmit" @keyup.enter="searchEnter">搜索
              </el-button>
            </el-form-item>
          </el-form>
        </div> -->
        <el-tree show-checkbox :data="data" :props="defaultProps" :expand-on-click-node="false" node-key="id"
          :default-expanded-keys="expanded" ref="tree" @check-change="checkChange">
          <template #default="{ node, data }">
            <div class="custom-tree-node" style="display:flex">
              <div style="flex:1">{{ node.label }}</div>

            </div>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="center-board" ref="wrap">
      <div class="operate">
        <!-- <el-button @click="goPreview" type="warning" plain>预览</el-button> -->
        <el-button @click="saveAll" type="primary" plain>保存</el-button>
        <!-- <el-button @click="publishAll" type="success" plain v-if="isTemplate == 0">发布</el-button> -->
        <el-button @click="clearAll" type="danger" plain>清空</el-button>
        <el-button type="info" plain @click="closeAll">关闭</el-button>
      </div>
      <el-form label-width="100px" :class="list.length == 0 ? 'm-empty' : ''" :label-position="labelPosition">
        <draggable :list="list" ref="draggable" class="draggable" @change="log2"
          :group="{ name: 'people', clone: 'false', put: true }" item-key="indexGlobal" animation="1000"
          ghost-class="ghost">
          <template #item="{ element, index }">
            <div @click="clickItem(index)" :class="element.isSelect == true ? ' select-bg' : ' unselect-bg'">
              <div class="delete" @click.stop="deleteItem(this, index)">
                <el-icon>
                  <Delete />
                </el-icon>
              </div>
              <div class="list-group-item-right">
                <div :class="labelPosition == 'top' ? 'index' : 'index-left'" v-if="showIndex">
                  {{ index + 1 }}. {{element.label}}
                </div>
                <div v-for="(item,idx) in element.children" class="children-item">
                  <div class="delete-children" @click.stop="deleteChildrenItem(this, index,idx)">
                    <el-icon>
                      <Remove />
                    </el-icon>
                  </div>
                  <el-form-item :label=" (index + 1)+'.'+(idx+1)+ ' '+item.label+'（'+item.code+'分）'" prop="name" :rules="[
                    { required: item.required, message: item.message },
                  ]">
                    <el-input placeholder="请填写分值" type="number"></el-input>
                  </el-form-item>
                </div>
              </div>

            </div>
          </template>
        </draggable>
      </el-form>
    </div>

  </div>
</template>
<script >
import draggable from "vuedraggable";
import { ElMessage, ElMessageBox } from "element-plus";
import { Eleme, Delete, Remove, Plus, CopyDocument } from "@element-plus/icons-vue";

import { httpService } from "@/utils/httpService";

export default {
  name: "custom-clone",
  display: "Custom Clone",
  order: 3,
  mounted() {
    this.uuid = this.$route.query.p;
    this.queryById();
    this.queryByReviewId();
    this.getTreeData()
  },

  watch: {
    value(newValue) {
      this.contentValue = newValue;
    },
    contentValue(newValue) {
      this.$emit("input", newValue);
    },
  },
  components: {
    draggable,
    Eleme,
    Delete, Remove,
    Plus,
    ElMessageBox,
    httpService,
    CopyDocument,
  },
  props: {
    value: {
      type: String,
      default: "",
    },
    disabled: {
      type: Boolean,
      default: false,
    },

  },
  data() {
    return {
      expanded: [],
      list: [],
      data: [

      ],
      form: {
        name: "",
        campusName: "",
      },
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      isTemplate: 0,
      marks: {
        0: "0",
        20: "20",
        40: "40",
        60: "60",
        80: "80",
        100: "100",
      },
      title: "",
      isTimeControl: 0,
      isPassword: 0,
      uuid: "",
      isAuthWx: "",
      isAuthWxIndex: true,
      voteUrl: "",
      tabVaule: "全局设置",
      labelPosition: "top",
      labelPositionIndex: true,
      daterange: [],
      password: "",
      finishMessage: "答题完毕，感谢您的作答！",
      lineWidth: 6,
      lineColor: "#000000",
      bgColor: "#f2f2f2",
      resultImg: "",
      isEdit: false,
      isCrop: false,

      contentValue: this.value,
      showIndex: true,
      showTimeIndex: true,
      showPasswordIndex: true,
      showFinishMessageIndex: true,

      isEmpty: true,
      list: [],
      indexGlobal: -1,
      questionnaireId: 0,

    };
  },
  methods: {
    goPreview() {
      this.$router.push({
        name: "preview",
        query: {
          p: this.uuid,
        },
      });
    },
    getTreeData() {

      httpService(
        "/javaApi/baseQuestionBank/queryTree",
        {
          "name": this.form.name,
          "campusName": this.form.campusName,
        },
        "get"
      ).then((data) => {
        console.log(data)
        this.data = data;
        console.log(this.data)

        console.log(this.expanded)
        this.expanded.push(data[0].id)
        console.log(this.expanded)

      });
    },
    queryById() {
      httpService(
        "/javaApi/evReview/queryById",
        "id=" + this.uuid,
        "post"
      ).then((data) => {
        if (data != "") {
          this.title = data.title;
        } else {
          // this.$router.push({
          //   path: "/noFound",
          // });
        }
      });
    },
    queryByReviewId() {
      httpService(
        "/javaApi/evReviewQuestion/queryTree",
        "reviewId=" + this.uuid,
        "post"
      ).then((data) => {
        if (data != "") {
          this.list = data;
        } else {
          // this.$router.push({
          //   path: "/noFound",
          // });
        }
      });
    },
    keyEnter() {
      //回车事件
      this.addItemName();
    },
    //form label显示位置
    changePositon(val) {
      if (val) {
        this.labelPosition = "top";
      } else {
        this.labelPosition = "left";
      }
      this.updateQustionnaire();
    },


    changeShowTimeIndex(val) {
      if (val) {
        this.isTimeControl = 1;
      } else {
        this.isTimeControl = 0;
      }
    },
    changeShowPasswordIndex(val) {
      if (val) {
        this.isPassword = 1;
      } else {
        this.isPassword = 0;
      }
    },
    // 添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
    // 需要什么事件可以自己增加
    onClick(e) {
      this.$emit("onClick", e, tinymce);
    },
    // 可以添加一些自己的自定义事件，如清空内容
    clear() {
      this.contentValue = "";
    },
    //移动是否可复制
    cloneMain() { },
    checkChange(checkedNodes, checkedKeys, halfCheckedNodes) {
      console.log("checkedNodes",checkedNodes)
      console.log("checkedKeys",checkedNodes)

      if (checkedKeys) {

        // let parent = this.$refs.tree.getNode(checkedNodes).parent
        // //当前为3级节点，则添加2级节点
        // if(checkedNodes.level==3){
        //   this.list.push(parent.data)
        // }else 
        //当前为2节点，则添加自己
        if (checkedNodes.level == 2) {
          if (!this.list.includes(checkedNodes)) {
            this.list.push(checkedNodes)
          }
        }else  if (checkedNodes.level == 1) {
          let children = checkedNodes.children;
          for(let i=0;i<children.length;i++){
            if (!this.list.includes(children[i])) {
            this.list.push(children[i])
            }
          }
        }
      }
      console.log(this.list)
    },
    //添加一项
    addItemName() {
      let item = {
        title: "选项" + (this.list[this.indexGlobal].items.length + 1),
      };
      this.list[this.indexGlobal].items.push(item);
    },
    //删除单选多选项
    deleteItemName(idx) {
      if (this.list[this.indexGlobal].items.length > 1) {
        this.list[this.indexGlobal].items.splice(idx, 1);
      } else {
        ElMessage.error("最少保留一项");
      }
    },
    //是否必填提示信息
    changeRadio() {
      let required = this.form.required;
    },
    //保存所有
    saveAll() {
      console.log("保存");
      console.log(this.list);
      if (this.list.length > 0) {
        let params = new FormData(); //创建一个form对象,必须是form对象否则后端接受不到数据
        let upList = JSON.stringify(this.list);
        params.append("json", upList);
        params.append("id", this.uuid);
        httpService("/javaApi/evReviewQuestion/publish", params, "post", {
          "Content-Type": "application/x-www-form-urlencoded",
        }).then((data) => {
          if (data.code == 200) {
            // this.$router.replace({
            //   path: "/publishResult",
            //   query: { url: data.obj },
            // });
            ElMessage.success("保存成功");

          } else {
            ElMessage.error("发布失败，请重试！");
          }
        });
      } else {
        ElMessage.error("没有任何题目，无需保存！");

      }

    },
    //发布所有
    publishAll() {
      console.log("发布");
      // 调用接口清空，清空后初始化
      let params = new FormData();
      params.append("id", this.questionnaireId);
      params.append("uuid", this.uuid);
      if (this.isAuthWx != null) {
        params.append("isAuthWx", this.isAuthWx);
      }
      if (this.voteUrl != null) {
        params.append("voteUrl", this.voteUrl);
      }
      httpService("/javaApi/qtQuestionnaire/publish", params, "post", {
        "Content-Type": "application/x-www-form-urlencoded",
      }).then((data) => {
        if (data.code == 200) {
          this.$router.replace({
            path: "/publishResult",
            query: { url: data.obj },
          });
        } else {
          ElMessage.error("发布失败，请重试！");
        }
      });
    },
    closeAll() {
      ElMessageBox.confirm("已保存本次设计吗？确定关闭吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          window.opener = null;
          window.open("", "_self");
          window.close();
        })
        .catch(() => { });
    },
    //清空所有
    clearAll() {
      ElMessageBox.confirm("确定要清空本次所有设计吗？", "提醒", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.list = [];
          this.indexGlobal = -1;
          // 调用接口清空，清空后初始化
          let params = new FormData();
          params.append("reviewId", this.uuid);
          httpService("/javaApi/evReviewQuestion/clearAll", params, "post").then(
            (data) => {
              if (data.code == 200) {
                ElMessage.success("清空成功");
                this.list = [];
              } else {
                // ElMessage.error("清空失败，请重试！");
              }
            }
          );
        })
        .catch(() => { });
    },
    //预览所有
    catAll() { },
    //点击添加
    addItem(index, element) {
      for (var i = 0; i < this.list.length; i++) {
        this.list[i].isSelect = false;
      }
      let item = JSON.parse(JSON.stringify(element)); //深拷贝
      item.isSelect = true;
      this.list.push(item);
      this.indexGlobal = this.list.length - 1;
      this.tabVaule = "题型设置";
      this.form = item;
      setTimeout(() => {
        let box = this.$el.querySelector(".draggable");
        box.scrollTop = box.scrollHeight;
      }, 100);
    },
    log: function (evt) { },
    sort: function (evt) {
      console.log(evt);
    },
    changeShowIndex(e) {
      this.updateQustionnaire();
    },

    changeIsAuthWxIndexIndex(e) {
      if (this.isAuthWxIndex == true) {
        this.isAuthWx = 1;
      } else {
        this.isAuthWx = 0;
      }
      this.updateQustionnaire();
    },
    changeShowFinishPasswordIndex(e) { },


    log2: function (evt) {
      let newIndex = 0;
      if (evt.moved) {
        newIndex = evt.moved.newIndex;
      }
      if (evt.added) {
        newIndex = evt.added.newIndex;
      }
      for (var i = 0; i < this.list.length; i++) {
        this.list[i].isSelect = false;
      }
      this.indexGlobal = newIndex;
      this.tabVaule = "题型设置";
      this.form = this.list[newIndex];
      this.list[newIndex].isSelect = true;
    },

    deleteItem(e, index) {
      this.indexGlobal = -1;
      this.form = {};
      this.list.splice(index, 1);
    },
    deleteChildrenItem(e, index, idx) {
      let item = this.list[index];
      let children = item.children;
      if (children.length > 1) {
        children.splice(idx, 1);
      } else {
        ElMessage.error("请至少保留一项！");
      }
    },
    onSubmit() {
      this.getTreeData();
    },
    copyItem(e, index) {
      this.indexGlobal = -1;
      console.log(this.list);
      let item = JSON.parse(JSON.stringify(this.list[index]));
      item.code = "";
      let items = item.items;
      for (let i = 0; i < items.length; i++) {
        items[i].code = "";
      }
      this.list.splice(index, 0, item);
      console.log(this.list);
      this.indexGlobal = index + 1;
      this.form = this.list[index + 1];
      for (var i = 0; i < this.list.length; i++) {
        this.list[i].isSelect = false;
      }
      this.list[index + 1].isSelect = true;
    },
    clickItem(index) {
      for (var i = 0; i < this.list.length; i++) {
        this.list[i].isSelect = false;
      }
      this.indexGlobal = index;
      this.tabVaule = "题型设置";
      this.form = this.list[index];
      this.list[index].isSelect = true;
      // 控制右侧显示
      console.log(this.list[index]);
    },

    cloneDog({
      type,
      label,
      isSelect,
      placeholder,
      required,
      line,
      message,
      items,
    }) {
      return {
        type: type,
        label: label,
        isSelect: isSelect,
        placeholder: placeholder,
        required: required,
        line: line,
        message: message,
        items: items,
      };
    },
  },
};
</script>
<style>
.el-tabs__content {
  border-left: 1px solid #dedede;
}

.el-tabs__item.is-active.is-focus {
  border: 0px solid red;
}

.el-rate__icon {
  font-size: 30px;
}

.el-tabs__header {
  padding: 0;
  position: relative;
  margin: 0 0 0px;
}

.el-radio {
  line-height: 32px;
}

.m-empty {
  background: url(../../assets/center_bg_2.png) no-repeat;
  background-repeat: no-repeat;
  background-position: center;
}

.el-switch__label span {
  line-height: 20px;
}

.el-switch {
  margin-left: 10px;
}

.el-divider {
  margin: 0px;
}
</style>
<style scoped>
.dateTimeRange {
  margin-bottom: 16px;
}

.mb-right {
  padding-left: 10px;
  padding-right: 10px;
  padding-bottom: 0px;
}

.ghost {
  border-top: 4px solid #409EFF;
}

.body {
  background: white;
  display: flex;
}

.delete-btn {
  margin-top: 10px;
}

.add-btn {
  margin-left: 80px;
}

.index {
  padding: 10px 10px 20px 0px;
  color: #409eff;
}

.m-line {
  background: #f2f2f2;
  height: 1px;
  margin-bottom: 10px;
}

.index-left {
  padding: 5px;
}

.delete {
  float: right;
  cursor: pointer;
  color: #f56c6c;
  padding: 5px;
  margin: 15px;
}

.delete-children {
  float: right;
  cursor: pointer;
}


.select-bg {
  border: 1px solid #409EFF;
  color: #606255;
  margin-top: 10px;
  background: white;
  border-radius: 4px;
}

.unselect-bg {
  border: 1px dashed #409EFF;
  background: white;
  margin-top: 10px;
  color: #606255;
  border-radius: 4px;
}

.list-group-item-right {
  cursor: move;
  /* display: flex; */
  padding: 20px;
}

.list-group-item-right:hover {
  background: white;
  border-radius: 6px;
}


.operate {
  font-weight: 600;
  height: 40px;
  line-height: 40px;
  text-align: right;
  font-size: 17px;
  padding-left: 20px;
  white-space: nowrap;
  background: white;
  padding-right: 20px;
}

.logo {
  color: #333333;
  font-weight: 600;
  height: 40px;
  line-height: 40px;
  font-size: 18px;
  padding-left: 10px;
  white-space: nowrap;
}

.logo-bottom {
  border-top: solid #dedede 1px;
  border-right: solid #dedede 1px;
  height: calc(100vh - 60px);
  padding: 10px;
}

.sub-title {
  text-align: right;
  vertical-align: middle;
  float: left;
  font-size: 14px;
  min-width: 100px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

.list-group-item-left {
  cursor: move;
  width: 50%;
}

.list-group-item-left .components-item {
  display: inline-block;
  width: calc(100% - 8px);
  margin: 4px;
  -webkit-transition: -webkit-transform 0ms !important;
  transition: -webkit-transform 0ms !important;
  transition: transform 0ms !important;
  transition: transform 0ms, -webkit-transform 0ms !important;
}

.item {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
}

.components-body:hover {
  border: 1px solid #409EFF;
  color: #409EFF;
}

.components-body {
  color: #707070;
  border: 1px solid #eaeaea;
  background-color: #fff;
  padding: 8px 10px;
  font-size: 16px;
  cursor: move;
  text-align: center;
  border-radius: 3px;
}

.components-title {
  font-size: 16px;
  color: #222;
  margin: 10px 2px;
  font-weight: bold;
}

.left-board {
  flex: 1;
  height: 100vh;
}

.center-board {
  height: 100vh;
  width: auto;
  flex: 2;
  background: #f3f5f6;
}

.draggable {
  height: calc(100vh - 80px);
  width: auto;

  overflow: scroll;
  border-top: 1px solid #dedede;
  padding: 10px 10px 30px 10px;
}


.right-content {
  width: calc(100% - 37px);
  height: calc(100vh - 60px);
  padding: 10px;
  overflow: auto;
}

.el-form-item--default {
  --font-size: 14px;
  --el-form-label-font-size: var(--font-size);
  margin-bottom: 18px;
  width: 100%;
}

.esign {
  max-width: 1000px;
  margin: auto;
  padding: 10px;
}

.esigh-btns button {
  color: #fff;
  height: 40px;
  width: 100px;
  font-size: 16px;
  margin-right: 10px;
  outline: none;
  border-radius: 4px;
  background: #f60;
  border: 1px solid transparent;
}

.esigh-btns button:active {
  color: #fff;
  box-shadow: 0px 0px 50px orangered inset;
}

.esigh-result {
  margin-top: 10px;
}

.esigh-result img {
  display: block;
  max-width: 100%;
  height: auto;
  border: 1px solid #ececee;
}

.esignature {
  margin: 10px 0;
  border: 1px solid #79bbff;
  border-radius: 4px;
}

.el-tabs__header {
  padding: 0;
  position: relative;
  margin: 0px;
}

.children-item {
  padding-left: 10px;
}

h3 {
  padding-left: 10px;
}

.demo-form-inline {
  display: flex;
}
</style>

